<template>
  <div>
    <el-breadcrumb separator="/" class="mb">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a>权限管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-button class="tj" type="primary" @click="isAddUser=true">添加角色</el-button>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-table :data="list" style="width: 100%">
        <el-table-column type="expand">
          <!-- 角色拥有权限 -->
          <template slot-scope="scope">
            <div v-if="scope.row.children.length>0">
              <el-row :class="['bot',index===0?'toborder':'']" @close="delte(scope.row, item1.id)" v-for="(item1,index) in scope.row.children" :key="item1.id">
                <!-- 一级权限 -->
                <el-col :span="6">
                  <el-tag type="primay" closable>{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-row v-for="item2 in scope.row.children" :key="item2.id" @close="delte(scope.row, item2.id)">
                    <!-- 二级权限 -->
                    <el-col :span="6">
                      <el-tag type="success" closable>{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级权限 -->
                    <el-col :span="18">
                      <el-tag type="warning" closable v-for="item3 in item2.children" :key="item3.id" @close="delte(scope.row,item3.id)">{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <hr />
            </div>
            <div v-else>暂无数据</div>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="roleDesc">
          <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)" icon="el-icon-edit" size="mini">编译</el-button>
            <el-button type="danger" @click="dele(scope.row.id)" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showHandel(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加角色 -->
      <el-dialog title="添加角色" :visible.sync="isAddUser">
        <el-form :ref="addData" :model="addData" :rules="addUserDiaRules">
          <el-form-item label="角色名称" prop="roleDesc" :label-width="formLabelWidth">
            <el-input v-model="addData.roleDesc" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="角色描述" prop="roleName" :label-width="formLabelWidth">
            <el-input v-model="addData.roleName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isAddUser = false">取 消</el-button>
          <el-button type="primary" @click="addUserConfirm(addData)">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改 -->
      <el-dialog title="添加角色" :visible.sync="isCompile">
        <el-form ref="EsUserDia" :model="addData" :rules="addUserDiaRules">
          <el-form-item label="角色名称" prop="roleDesc" :label-width="formLabelWidth">
            <el-input v-model="addData.roleDesc" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="角色描述" prop="roleName" :label-width="formLabelWidth">
            <el-input v-model="addData.roleName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isCompile = false">取 消</el-button>
          <el-button type="primary" @click="editHandel">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分配权限弹窗 -->

      <el-dialog title="分配权限" :visible.sync="isSetingRights" width="30%">
        <el-tree ref="treeRef" node-key="id" :data="rightData" :default-checked-keys="checkedKeysArr" show-checkbox :props="defaultProps" default-expand-all></el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isSetingRights = false">取 消</el-button>
          <el-button type="primary" @click="seHandel">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [],
      isAddUser: false,
      userid: "",
      formLabelWidth: "120px",
      currid: "",
      //  修改
      isCompile: false,
      isSetingRights: false,
      rightData: [],
      checkedKeysArr: [],
      defaultProps: {
        children: "children",
        label: "authName"
      },
      addData: {
        roleDesc: "龟康",
        roleName: "真帅"
      },
      addUserDiaRules: {
        roleDesc: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" }
        ],
        roleName: [
          { required: true, message: "请输角色描述", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 删除角色权限
    delte(row, rightId) {
      console.log("row", row);
      console.log("rightId", rightId);
      console.log(11111111);

      this.$axios.delete(`/roles/${row.id}/rights/${rightId}`).then(res => {
        row.children = res;
        console.log("删除后剩余权限：", res);
      this.$message({
        type: "success",
        message: "删除成功"
      });
         this.getlist()
      });
    },

    // 分配权限弹窗
    async showHandel(row) {
      this.checkedKeysArr = [];
      this.userid = row.id;
      const res = await this.$axios.get(`/rights/tree`);
      this.getCheckedRightsIds(row, this.checkedKeysArr);
      console.log("树形权限列表", res);

      this.rightData = res.data.data;
      this.isSetingRights = true;
    },
    // 点击确定 分配权限
    async seHandel() {
      let arr = [
        //全选中
        ...this.$refs.treeRef.getCheckedKeys(),
        //半选中
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      this.isSetingRights = false;
      console.log("node:", arr);
      let nodeStr = arr.join(",");
      const res = await this.$axios.post(`/roles/${this.userid}/rights`, {
        rids: nodeStr
      });
      console.log("分配成功结果：", res);
      this.getlist();
      this.isSetingRights = false;
    },
    // 递归
    getCheckedRightsIds(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }

      //如果node含有children，则用递用调用getCheckedRightsIds函数
      node.children.forEach(subnode => this.getCheckedRightsIds(subnode, arr));
    },

    // 权限管理删除
    // delte(row, rightId) {
    //   console.log(row);

    //   console.log("id", id);

    //   this.$axios.delete(`/roles/${row.id}/rights/${rightId}`).then(res => {
    //     row.children = res;
    //     // console.log("删除后剩余权限：", res);

    //     //  this.getlist()
    //   });

    //   // const res = await this.$axios.delete(`/roles/${id}`);
    //   // this.$message({
    //   //   type: "success",
    //   //   message: "删除成功"
    //   // });

    //   // this.getlist();
    // },

    // 出现修改弹窗
    edit(row) {
      this.isCompile = true;
      this.currid = row.id;
      this.addData = row;
    },
    // 修改
    editHandel() {
      console.log(1);
      this.$refs.EsUserDia.validate(async valid => {
        if (!valid) return;
        this.$axios.put(`/roles/${this.currid}`, this.addData);
        this.isCompile = false;
      });
    },

    // 添加
    addUserConfirm(addData) {
      this.$refs[addData].validate(valid => {
        if (valid) {
          this.$axios.post("roles", this.addData).then(res => {
            this.getlist();
          });
          this.isAddUser = false;
        } else {
          return false;
        }
      });
    },
    async getlist() {
      const res = await this.$axios.get("roles");
      // 表格数据
      this.list = res.data.data;

      console.log(this.list);
    },
    async dele(id) {
      console.log(1);

      console.log(id);
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);

      if (res !== "confirm") {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      } else {
        await this.$axios.delete(`roles/${id}`);
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.getlist();
      }
    }
  },
  mounted() {
    this.getlist();
  }
};
</script>

<style lang="scss" scoped>
.mb {
  margin-bottom: 20px;
}
.tj {
  margin-bottom: 10px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.toborder {
  border-top: 1px solid #eee;
}
.bot {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 6px;
}
</style>